<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <title>Title</title>
</head>
<body>
<p class='p1'></p>
<p class='p2'></p>
<p class='p3'></p>
<script>
  let str1 = 'hello world'
  //将str中的l颜色变为红色
  str1 = str1.replace(/l/gi, match => {
    return `<span style='color: red'>${match}</span>`
  })
  document.querySelector('.p1').innerHTML = str1

  let str2 = 'abcacdabac'
  //将str中的a和c颜色变为红色
  str2 = str2.replace(/a|c/gi, match => {
    return `<span style='color: red'>${match}</span>`
  })
  document.querySelector('.p2').innerHTML = str2

  // 封装成函数
  function highlight (str, keyword) {
    return str.replace(new RegExp(keyword, 'gi'), match => {
      return `<span style='color: red'>${match}</span>`
    })
  }

  let str3 = '好好学习，天天向上'
  document.querySelector('.p3').innerHTML = highlight(str3, '好|天')
</script>
</body>
</html>
